<template>

  <el-card class="TopCard" style="height:680px">
    <!-- 小喇叭 -->
    <i class="el-icon-chat-dot-round" style="color:#606266"/>
    <span class="tips">公告：</span>
    <!-- 滚动文字外层div，文字能展示的区域-->
    <div class="noticeBox" :style="'width:'+noticeWidth+'px;height:20px;position:relative;overflow:hidden;display:inline-block;vertical-align:middle;margin-top:-5px'">
      <!-- 滚动div，marginLeft变化-->
      <div :style="'margin-left:'+marginLeft+'px;white-space:nowrap'">
        <span class="showNotice">{{showNotice}}</span>
        <!-- 不会展示，用来测量第二条与第一条重合时的长度 -->
        <span class="notice">{{notice}}</span>
      </div>
    </div>

  <el-card class="TopCard" style="height:600px;margin-right:-10px;margin-top:10px">

    <!--    功能区域-->
    <!-- <div style="margin: 10px 0">
      <el-button type="primary" @click="add">新增</el-button>
    </div> -->

    <!--    搜索区域-->
    <div style="margin: 10px 0">
      <el-input v-model="search" placeholder="请输入标题关键字" style="width: 20%" clearable></el-input>
      <el-button type="primary" style="margin-left: 5px" @click="load">查询</el-button>
    </div>
    <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%">
      <el-table-column
          prop="id"
          label="ID"
          sortable
      >
      </el-table-column>
      <el-table-column
          prop="title"
          label="标题">
      </el-table-column>
      <el-table-column
          prop="author"
          label="发布者"
          sortable
      >
      </el-table-column>
      <el-table-column
          prop="time"
          label="发布时间"
          sortable
      >
      </el-table-column>
      <el-table-column label="">
        <template #default="scope">
          <el-button size="mini" @click="details(scope.row)">详情</el-button>
          <!-- <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm title="确定删除吗？" @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button size="mini" type="danger">删除</el-button>
            </template>
          </el-popconfirm> -->
        </template>
      </el-table-column>
    </el-table>

    <div style="margin: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!-- <el-dialog title="提示" v-model="dialogVisible" width="50%">
      <el-form :model="form" label-width="120px">
        <el-form-item label="标题">
          <el-input v-model="form.title" style="width: 50%"></el-input>
        </el-form-item>

        <div id="div1"></div> -->
        <!-- 原本就注释 -->
        <!--        <el-form-item label="内容">-->
        <!--          <el-input v-model="form.price" style="width: 80%"></el-input>-->
        <!--        </el-form-item>-->
        <!-- 原本就注释 -->
      <!-- </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
          </span>
      </template>
    </el-dialog> -->

    <el-dialog title="详情" v-model="vis" width="50%">
      <el-card>
        <div v-html="detail.content" style="min-height: 100px"></div>
      </el-card>
    </el-dialog>

 </el-card>
   </el-card>
</template>

<script>
import E from 'wangeditor'
import request from "@/utils/request";

export default {
  name: 'Home',
  components: {},
  data () {
    return {
      // 适应屏幕分辨率
      noticeWidth: window.screen.width - 150,
      // 公告展示（过长时会重复两遍）
      showNotice: '',
      // 用于公告过长时，获取重复两遍中第一遍的长度
      notice: '',
      // 公告初始位置
      marginLeft: 100,
      //以下是News
      loading: true,
      form: {},
      dialogVisible: false,
      search: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      vis: false,
      detail: {},
      
    }
  },
  
  mounted () {
    this.noticeData = []
    request.get("/news").then((res) => {
        if (res.code === "0") {
          res.data.records.forEach((item) => {
            this.noticeData.push(item.title
            );
            console.log(item.title)
          });
          // console.log(res.data.records[0].title)
          this.noticeData = this.noticeData.reverse() //数组倒序，输出最后添加的通告（最新通告）
    this.noticeData.forEach((val, index) => {
      if (index === 0) {
        this.showNotice += '【' + (index + 1) + '】' + val
      } else {
        this.showNotice += '\xa0\xa0\xa0\xa0\xa0\xa0【' + (index + 1) + '】' + val
      }
    })
    // 公告上面先赋值，再获取宽度
    setTimeout(() => {
      // 公告div长度
      var oneNoticeWidth = document.getElementsByClassName('showNotice')[0].offsetWidth
      // 公告外层div长度
      var noticeBoxWidth = document.getElementsByClassName('noticeBox')[0].offsetWidth
      // 一条公告长度太大时，才滚动
      if (oneNoticeWidth > noticeBoxWidth) {
        // 滚动公告需要将公告重复两遍进行滚动，两遍中间需要加空格
        this.notice = this.showNotice + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0'
        // 上面先赋值，再获取宽度
        setTimeout(() => {
          // 获取一遍加中间空格的长度，即左移时第二遍与第一遍完全重合时的长度
          var oneNoticeAddEmptyWidth = document.getElementsByClassName('notice')[0].offsetWidth
          // 公告内容重复两遍
          this.showNotice = this.notice + this.showNotice
          this.timer = setInterval(() => {
            this.marginLeft -= 1
            // 第二遍与第一遍起始位置重合时（第一条已完全移到左侧隐藏），marginLeft置0，即回到第一条
            if (this.marginLeft === (-1) * oneNoticeAddEmptyWidth) {
              this.marginLeft = 0
            }
          }, 20)
        }, 10)
      } else { //公告并没有很长时不滚动
        this.marginLeft = 0
      }
    }, 10)

        }
      });
    console.log(this.noticeData)
    
    
    // this.noticeData = ['公告二', '公告一 公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一公告一']
    
    
    
  },
  created() {
    this.load()
  },
  methods: {
    details(row) {
      this.detail = row
      this.vis = true
    },
    filesUploadSuccess(res) {
      console.log(res)
      this.form.cover = res.data
 
    },
    load() {
      this.loading = true
      request.get("/news", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          search: this.search
        }
      }).then(res => {
        this.loading = false
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    add() {
      this.dialogVisible = true
      this.form = {}

      this.$nextTick(() => {
        // 关联弹窗里面的div，new一个 editor对象
        if (!editor) {
          editor = new E('#div1')

          // 配置 server 接口地址
          editor.config.uploadImgServer = 'http://' + window.server.filesUploadUrl + ':9090/files/editor/upload'
          editor.config.uploadFileName = "file"  // 设置上传参数名称
          editor.create()
        }

        editor.txt.html("")

      })

    },
    save() {
      this.form.content = editor.txt.html()  // 获取 编辑器里面的值，然后赋予到实体当中

      if (this.form.id) {  // 更新
        request.put("/news", this.form).then(res => {
          console.log(res)
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "更新成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load() // 刷新表格的数据
          this.dialogVisible = false  // 关闭弹窗
        })
      } else {  // 新增
        let userStr = sessionStorage.getItem("user") || "{}"
        let user = JSON.parse(userStr)
        this.form.author = user.nickName

        request.post("/news", this.form).then(res => {
          console.log(res)
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "新增成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }

          this.load() // 刷新表格的数据
          this.dialogVisible = false  // 关闭弹窗
        })
      }

    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true

      this.$nextTick(() => {
        // 关联弹窗里面的div，new一个 editor对象
        // 关联弹窗里面的div，new一个 editor对象
        if (!editor) {
          editor = new E('#div1')

          // 配置 server 接口地址
          editor.config.uploadImgServer = 'http://localhost:9090/files/editor/upload'
          editor.config.uploadFileName = "file"  // 设置上传参数名称
          editor.create()
        }

        editor.txt.html(row.content)
      })
    },
    // handleDelete(id) {
    //   console.log(id)
    //   request.delete("/news/" + id).then(res => {
    //     if (res.code === '0') {
    //       this.$message({
    //         type: "success",
    //         message: "删除成功"
    //       })
    //     } else {
    //       this.$message({
    //         type: "error",
    //         message: res.msg
    //       })
    //     }
    //     this.load()  // 删除之后重新加载表格的数据
    //   })
    // },
    handleSizeChange(pageSize) {   // 改变当前每页的个数触发
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {  // 改变当前页码触发
      this.currentPage = pageNum
      this.load()
    }
  }
  
}
</script>
<style >
/* 公告card */
.TopCard .el-card__body{
  padding:0px 10px
  
}
/* 公告title */
.tips{
  line-height:50px;
  color:#606266;
  font-weight:bold
}
</style>